package com.estronger.shopmanage.adapter;

import android.Manifest;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.shopmanage.gaodemap.LocationActivity;
import com.estronger.shopmanage.ui.common.ConfirmActivity;
import com.estronger.shopmanage.ui.measure.MeasureActivity;
import com.estronger.shopmanage.ui.measure.MeasureDetailActivity;
import com.estronger.shopmanage.ui.measure.MeasureInputActivity;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseHolder;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B10MeasureList.MeasureListData;
import com.estronger.shopmanage.bean.B11Designer;
import com.estronger.shopmanage.bean.B13GetTask;
import com.estronger.shopmanage.fragment.FragmentFactory;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.manager.PopManager;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.estronger.shopmanage.utils.TimeUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.AppDialog;
import com.google.gson.Gson;
import com.lidroid.xutils.http.RequestParams;
import com.soonfor.evaluate.tools.CommonUtils;
import com.tbruyelle.rxpermissions2.Permission;

import java.util.List;

public class MeasureAdapter extends DefaultAdapter<MeasureListData> {

	private MeasureActivity mContext;
	private Gson gson;
	protected static final short READY_RECEIVE = 0;
	protected static final short READY_CONTACT = 1;
	protected static final short READY_ARRIVE = 2;
	private Dialog dialog;
	private View needDeleteView = null;
	private String needDeleteId = "";
	private boolean isAll;

	public MeasureAdapter(MeasureActivity measureActivity,
			List<MeasureListData> datas, Gson gson, boolean isAll) {
		super(datas);
		this.mContext = measureActivity;
		this.gson = gson;
		this.isAll = isAll;
	}

	@Override
	protected BaseHolder getHolder() {
		return new HistoryHoder();
	}

	// 当删除一个条目的动画执行完之后调用
	protected void deleteItem(String measureid) {
		if (TextUtils.isEmpty(measureid)) {
			return;
		}
		for (int i = 0; i < datas.size(); i++) {
			if ((datas.get(i).measureid).equals(measureid)) {
				datas.remove(datas.get(i));
				notifyDataSetChanged();
			}
		}

	}

	/**
	 * @author Administrator 一个Adapter配一个Hoder的意思吧
	 */
	class HistoryHoder extends BaseHolder<MeasureListData> implements
			OnClickListener {
		ViewGroup deleteItem;
		public TextView item_name, item_phone, appointment, appointment_time,
				item_describle, location;
		public ImageView state, call, sms;
		public TextView item_colleagues, item_receive,tvTaskType;
		private RelativeLayout layout;
		public LinearLayout item_phone_rb, item_result, item_bottom;
		public LinearLayout phone_appointement;//电话预约
		public LinearLayout appointment_checkin;//预约登记
		private PopManager popManager;
		private RequestParams params;
		private View item_line;
		boolean needResult = true;

		/**
		 * 主要是处理一个测量任务条目里面的各种点击事件 比如R.id.item_colleagues是转给其他同事的处理
		 */
		@Override
		public void onClick(final View v) {
			String measureid = v.getTag().toString();
			Intent intent;
			switch (v.getId()) {
			case R.id.item_colleagues:// 测量条件确认
				params = new RequestParams();
				params.addBodyParameter("sf_action", "geteditdesignerdata");
				params.addBodyParameter("usercode", MyApplication.getUserCode());
				params.addBodyParameter("measureid", measureid);
				netManager.connectWork(params, NetManager.DESIGNERS);
				if (null == popManager) {
					popManager = new PopManager(mContext);
					popManager.initTransPop(measureid);
				}
				if (null == popManager.getTransPop()) {
					popManager.initTransPop(measureid);
				}
				popManager.showTransPop(mContext.getRoot(),
						((View) v.getParent()).getTag().toString());
				break;
			case R.id.measure_send_sms:// 点击了测量条目上的发短信小图标
				String number1 = item_phone.getText().toString();
				if (mContext.isRightNumber(number1)) {
					Uri uri = Uri.parse("smsto:" + number1);
					intent = new Intent(Intent.ACTION_SENDTO, uri);
					mContext.startActivity(intent);
				}
				break;
			case R.id.measure_phone_call:// 点击了测量条目上的电话小图标
			case R.id.phone_appointement: // 点击了测量条目上的与客户确认预约
				String number = item_phone.getText().toString();
				if (mContext.isRightNumber(number)) {
					dialog = AppDialog.createDialog(mContext,
							this.data.cstname, number, this, measureid);
					if (v.getId() == R.id.phone_appointement) {
						needResult = true;
					} else {
						needResult = false;
					}
					dialog.show();
				}
				break;
				case R.id.appointment_checkin:
					intent = new Intent(mContext, ConfirmActivity.class);
					intent.putExtra("measureid", measureid + "");
					intent.putExtra("taskid", 1);
					mContext.startActivityForResult(intent,
							MeasureActivity.REFLESH_DATA);
					break;
			case R.id.item_result:// 跳转到测量结果输入
				intent = new Intent(mContext, MeasureInputActivity.class);
				intent.putExtra("measureid", measureid);
				mContext.startActivityForResult(intent,
						MeasureActivity.REFLESH_DATA);
				break;
			case R.id.item_receive:// 领取任务
				params = new RequestParams();
				params.addBodyParameter("sf_action", "accepttask");
				params.addBodyParameter("usercode", MyApplication.getUserCode());
				params.addBodyParameter("measureid", measureid);
				netManager.connectWork(params, NetManager.GET_TASK);
				mContext.setProgresVisible(true);
				View v2 = (View) ((View) (v.getParent())).getParent();
				needDeleteView = (View) (((ViewGroup) v2.getParent())
						.getParent());
				needDeleteId = measureid;
				break;
			case R.id.measure_item:// 一个测量任务条目被点击了跳转到测量详情
				measureid = ((RelativeLayout) v)
						.findViewById(R.id.item_phone_rb).getTag().toString();
				String complesh = v.findViewById(R.id.item_state).getTag()
						.toString();
				boolean isComplesh = false;
				if (complesh.equals("1")) {
					isComplesh = true;
				}

				intent = new Intent(mContext, MeasureDetailActivity.class);
				intent.putExtra("measureid", measureid);
				intent.putExtra("isComplesh", isComplesh);
				mContext.startActivity(intent);
				break;
			case R.id.ok:// 点击了联系客户的对话框的确定按钮的处理
				String number2 = item_phone.getText().toString();
				intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
						+ number2));
				if (needResult) {// 这里是判断拨打电话后是否需要跳转到与客户确认预约的界面
					MeasureActivity.CALL_RESULT = Integer.valueOf(measureid);
					mContext.startActivityForResult(intent,
							MeasureActivity.CALL_RESULT);
				} else {
					mContext.startActivity(intent);
				}
				dialog.dismiss();
				break;
			case R.id.measure_item_location:// 进入高德地址选择界面
				PermissionUtils.getInstance().requestPromisssions(mContext, new PermissionUtils.AcceptListener() {
					@Override
					public void grante() {
						TextView tv = (TextView) v;
						String add = tv.getText().toString().trim();
						if(!add.equals("")) {
							Intent intent = new Intent(mContext, LocationActivity.class);
							intent.putExtra("latitude", "");
							intent.putExtra("location", add);
							intent.putExtra("longtitude", "");
							mContext.startActivityForResult(intent, 8889);
						} else {
							Toast.show(mContext, "测量客户地址为空", 2000);
						}
					}

					@Override
					public void denial(Permission permission) {

					}

					@Override
					public void fail() {

					}
				},Manifest.permission.ACCESS_COARSE_LOCATION,
						Manifest.permission.ACCESS_FINE_LOCATION);
				break;
			}
		}

		/**
		 * 当前activity所有联网成功的回调
		 * 
		 * @params code 各个接口返回的唯一识别码，用来判断是哪个接口成功返回
		 * @params result 网络请求成功返回的数据
		 */
		@Override
		protected void onNetSuccess(int code, String result) {
			if (NetManager.GET_TASK == code) {
				B13GetTask task = gson.fromJson(result, B13GetTask.class);
				if (mContext != null) {
					mContext.getTaskResult(task.success);
				}
				if (task.success && needDeleteView != null) {
					removeAnim(needDeleteView.getHeight(), needDeleteView);
				}
			}
			mContext.setProgresVisible(false);

			if (NetManager.DESIGNERS == code) {
				B11Designer designer = gson.fromJson(result, B11Designer.class);
				if (designer.success) {
					popManager.refleshTransPop(designer);
				}
			}
		}

		@Override
		protected void onNetErorr(int code, String result) {
			mContext.setProgresVisible(false);
			needDeleteView = null;
		}

		/**
		 * 初始化一个测量条目中的内容
		 */
		@Override
		public View initView() {
			View view = null;
			view = View.inflate(mContext, R.layout.measure_item, null);

			item_name = (TextView) view.findViewById(R.id.measure_item_name);
			item_phone = (TextView) view.findViewById(R.id.measure_item_phone);
			appointment = (TextView) view
					.findViewById(R.id.measure_item_appointment);
			appointment_time = (TextView) view
					.findViewById(R.id.measure_item_appointment_time);
			item_describle = (TextView) view
					.findViewById(R.id.measure_item_describle);
			location = (TextView) view.findViewById(R.id.measure_item_location);
			layout = (RelativeLayout) view
					.findViewById(R.id.colleagues_phone_layout);
			item_bottom = (LinearLayout) view
					.findViewById(R.id.measure_item_bottom);
			state = (ImageView) view.findViewById(R.id.item_state);
			item_colleagues = (TextView) view
					.findViewById(R.id.item_colleagues);
			item_line = view.findViewById(R.id.measure_item_line);

			item_phone_rb = (LinearLayout) view
					.findViewById(R.id.item_phone_rb);
			item_result = (LinearLayout) view.findViewById(R.id.item_result);
			item_receive = (TextView) view.findViewById(R.id.item_receive);

			call = (ImageView) view.findViewById(R.id.measure_phone_call);
			sms = (ImageView) view.findViewById(R.id.measure_send_sms);

			appointment_checkin = view.findViewById(R.id.appointment_checkin);
			phone_appointement = view.findViewById(R.id.phone_appointement);
			tvTaskType = view.findViewById(R.id.task_type);

			if (isAll) {
				item_bottom.setVisibility(View.GONE);
				item_line.setVisibility(View.GONE);
			}
			sms.setOnClickListener(this);
			sms.setTag("无用");
			call.setOnClickListener(this);
			call.setTag("无用");
			location.setTag("无用");
			location.setOnClickListener(this);
			view.setOnClickListener(this);
			return view;
		}

		@Override
		public void refreshView(MeasureListData data) {
			if (TextUtils.isEmpty(data.cstbuildname)) {
				item_name.setText(CommonUtils.formatStr(data.cstname));
			} else {
				item_name.setText(CommonUtils.formatStr(data.cstbuildname) + "-" + CommonUtils.formatStr(data.cstname));
			}
			layout.setTag(data.cstname);
			item_phone.setText(data.cstmobile + "");
			String prtxt = data.measurestatus.equals("1")?"完成时间：":"预约时间：";
			appointment.setText(prtxt + data.getPlanmeasuredate());
			if(data.firstdemand==null || data.firstdemand.equals("")){
				item_describle.setVisibility(View.GONE);
			}else {
				item_describle.setVisibility(View.VISIBLE);
				item_describle.setText("初步需求:" + data.firstdemand);
			}
			tvTaskType.setText(!TextUtils.isEmpty(data.typedesc)?("任务类型:" + data.typedesc):"");
			location.setText(data.address);
			appointment_time.setVisibility(data.measurestatus.equals("1")?View.GONE:View.VISIBLE);
			appointment_time.setText(TimeUtils.chaZhi(data.planmeasuredate));
			/*
			 * 转给其他同事 领取 与客户预约 测量结果输入按钮的点击事件都需要measureid
			 */
			item_colleagues.setTag(data.measureid);
			item_result.setTag(data.measureid);
			item_receive.setTag(data.measureid);
			item_phone_rb.setTag(data.measureid);
			appointment_checkin.setTag(data.measureid);
			phone_appointement.setTag(data.measureid);
			/*
			 * 转给其他同事 领取 与客户预约 测量结果输入按钮的点击事件都由本对象来处理
			 */
			item_colleagues.setOnClickListener(this);
			item_result.setOnClickListener(this);
			item_receive.setOnClickListener(this);

			phone_appointement.setOnClickListener(this);
			appointment_checkin.setOnClickListener(this);

			if (!TextUtils.isEmpty(data.status.trim())) {
				int code = Integer.valueOf(data.status);
				state.setTag("0");
				switch (code) {// 根据status的值来确定显示哪张状态图
				case READY_RECEIVE:// 显示带领取图
					state.setImageResource(R.drawable.state_receive_icon);
					break;
				case READY_CONTACT:// 显示待联系图
					state.setImageResource(R.drawable.state_appointment_icon);
					layout.setVisibility(View.GONE);
					item_phone_rb.setVisibility(View.VISIBLE);
					break;
				case READY_ARRIVE:// 显示待上门图
					state.setImageResource(R.drawable.state_measure_icon);
					layout.setVisibility(View.GONE);
					item_phone_rb.setVisibility(View.GONE);
					item_result.setVisibility(View.VISIBLE);
					break;
				}
			}

			if (data.measurestatus.equals("1")) {
				state.setImageResource(R.drawable.state_complete_icon);
				layout.setVisibility(View.GONE);
				state.setTag("1");
			}
		}
	}

	/**
	 * @param startHeight
	 *            控件的高度
	 * @param v
	 *            执行动画的控件
	 */
	private void removeAnim(int startHeight, final View v) {
		if (v == null)
			return;
		ValueAnimator animator = ValueAnimator.ofInt(startHeight, 0);
		animator.addUpdateListener(new AnimatorUpdateListener() {

			@Override
			public void onAnimationUpdate(ValueAnimator animation) {
				int value = (Integer) animation.getAnimatedValue();
				LayoutParams params = v.getLayoutParams();
				params.height = value;
				v.setLayoutParams(params);
			}
		});
		animator.addListener(new AnimatorListener() {

			@Override
			public void onAnimationStart(Animator arg0) {
			}

			@Override
			public void onAnimationRepeat(Animator arg0) {
			}

			@Override
			public void onAnimationEnd(Animator arg0) {
				deleteItem(needDeleteId);
				FragmentFactory.createFragment(mContext.getCurrPosition())
						.connect(mContext.getCurrPosition() + "");
			}

			@Override
			public void onAnimationCancel(Animator arg0) {

			}
		});
		animator.setDuration(500);
		animator.start();
	}
}
